package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.PageResult;
import com.heima.mapper.SkuMapper;
import com.heima.pojo.dto.PageSku;
import com.heima.pojo.Sku;
import com.heima.pojo.dto.SkuDto;
import com.heima.pojo.vo.BusinessTop10Vo;
import com.heima.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class SkuServiceImpl implements SkuService {

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 新增商品
     * @param skuDto
     * @return
     */
    @Override
    public Boolean saveSku(SkuDto skuDto) {
        Sku sku = new Sku();
        BeanUtils.copyProperties(skuDto, sku);
        Integer math = skuMapper.insertSku(sku);
        return math > 0;
    }

    /**
     * 搜索
     * @param pageSku
     * @return
     */
    @Override
    public PageResult<Sku> search(PageSku pageSku) {
        PageHelper.startPage(pageSku.getPageIndex(), pageSku.getPageSize());
        Page<Sku> list = skuMapper.findByName(pageSku);
        // 计算总页数
        int totalPage = (int) Math.ceil((double) list.getTotal() / pageSku.getPageSize());
        return new PageResult<>(
                pageSku.getPageIndex(),
                pageSku.getPageSize(),
                totalPage,
                list.getTotal(),
                list.getResult()
        );
    }

    /**
     * 修改SKU
     * @param skuDto
     * @return
     */
    @Override
    public Boolean updateSku(SkuDto skuDto) {
        Sku sku = new Sku();
        BeanUtils.copyProperties(skuDto, sku);
        Integer math = skuMapper.modifySku(sku);
        return math > 0;
    }

    /**
     * 商圈下销售前10的商品
     * Todo
     * @param businessId
     * @return
     */
    @Override
    public List<BusinessTop10Vo> businessTop10(Integer businessId) {
        return skuMapper.getTop(businessId);
    }
}
